import os
import time
from random import randint
from urllib.request import Request, urlopen
import getLocate as gl
import _locale
_locale._getdefaultlocale = (lambda *args: ['zh_CN', 'utf8'])
# coding=utf-8
import cs2downloads as cs2

currentVersion = '1.0.1'
print(f"Welcome to PYCS2CfgUpdater v{currentVersion}")
time.sleep(1)
print("Checking update...")
try :
    headers = {'User-Agent': f'Mozilla/5.0 {randint(1000,9999)} Windows NT 10.0'}
    url = f'https://v.cssummer.top/pycs2/v.html'
    url = Request(url, headers=headers)
    try:
        onlinev=urlopen(url,timeout=15).read().decode('utf-8')
        print(f"Online Version is v{onlinev}")
    except Exception as e:
        print(f"Error \n{e}")
except Exception as e:
    print(f"Network Error!{e}")
if onlinev == currentVersion:
    print("Your version is up to date!")
else:
    print("Your version is down to date!You should update as fast as possible!")

def download(vs):
    if cs2.download(currentVersion=currentVersion):
        if cs2.unzip():
            np = os.getcwd()
            unzippath = np + "\zipped"
            files_in_dir = os.listdir(unzippath)
            cfgs = [f for f in files_in_dir if os.path.isfile(os.path.join(unzippath, f))]
            for i in cfgs:
                cs2.mvfile(unzippath + f"\{i}", cfgAddr)
print("Getting CS2 Folder...")
wins = gl.gets()
if wins[0] and wins[1]:
    print("Folder already found!")
addr = wins[0]
print(f"CS2 Addr:{addr}")
cfgAddr=addr + "\game\csgo\cfg"
print(f"CFG Addr:{cfgAddr}")
print("Reading Cfg file version...")
pracaddr = cfgAddr+"\prac.cfg"
print(f"Prac.cfg Addr:{pracaddr}")
try:
    f = open(pracaddr, 'r', encoding='utf-8')
    v = f.readline().split('v')[-1]
    if currentVersion in v:
        print("Your config file is up to date！")
    else:
        print("Your config file is down to date!")
        time.sleep(2)
        print("Redirecting to download....")
        os.system("cls")
        download(onlinev)
except Exception as e:
    time.sleep(1)
    print(f"Error! \n{e}")
    print("No file found. Now downloading -> go_to_download")
    download(onlinev)